package com.nanjia.boot.myflow.outboundorderdetail.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanjia.boot.batch_stock.mapper.WarehouseBatchStockMapper;
import com.nanjia.boot.batch_stock.model.entity.WarehouseBatchStock;
import com.nanjia.boot.common.enums.OrderStatusEnum;
import com.nanjia.boot.common.result.Result;
import com.nanjia.boot.core.security.util.SecurityUtils;
import com.nanjia.boot.myflow.order.mapper.OrderMapper;
import com.nanjia.boot.myflow.order.model.entity.Order;
import com.nanjia.boot.myflow.order.item.mapper.OrderItemMapper;
import com.nanjia.boot.myflow.order.item.model.entity.OrderItem;
import com.nanjia.boot.outboundorder.mapper.OutboundOrderMapper;
import com.nanjia.boot.outboundorder.model.entity.OutboundOrder;
import com.nanjia.boot.myflow.outboundorderdetail.converter.OutboundOrderDetailConverter;
import com.nanjia.boot.myflow.outboundorderdetail.mapper.OutboundOrderDetailMapper;
import com.nanjia.boot.myflow.outboundorderdetail.model.entity.OutboundOrderDetail;
import com.nanjia.boot.myflow.outboundorderdetail.model.form.OutboundOrderDetailForm;
import com.nanjia.boot.myflow.outboundorderdetail.model.query.OutboundOrderDetailQuery;
import com.nanjia.boot.myflow.outboundorderdetail.model.vo.OutboundOrderDetailVO;
import com.nanjia.boot.myflow.outboundorderdetail.service.OutboundOrderDetailService;
import com.nanjia.boot.product.sku.mapper.ProductSkuMapper;
import com.nanjia.boot.stock.productbatch.mapper.ProductBatchMapper;
import com.nanjia.boot.stock.productbatch.model.entity.ProductBatch;
import com.nanjia.boot.warehouse.mapper.WarehouseMapper;
import com.nanjia.boot.warehouse.model.entity.Warehouse;
import com.nanjia.boot.warehouse.storagelocation.mapper.WarehouseStorageLocationMapper;
import com.nanjia.boot.warehouse.storagelocation.model.entity.WarehouseStorageLocation;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 出库明细服务实现类
 *
 * @author 周洋
 * @since 2025-08-22 18:01
 */
@Service
@RequiredArgsConstructor
public class OutboundOrderDetailServiceImpl extends ServiceImpl<OutboundOrderDetailMapper, OutboundOrderDetail> implements OutboundOrderDetailService {

    private final OutboundOrderDetailConverter outboundOrderDetailConverter;
    private final ProductBatchMapper productBatchMapper;

    private final OutboundOrderDetailMapper outboundOrderDetailMapper;

    private final OutboundOrderMapper outboundOrderMapper;

    private final OrderMapper orderMapper;

    private final ProductSkuMapper productSkuMapper;

    private final OrderItemMapper orderItemMapper;

    private final WarehouseBatchStockMapper warehouseBatchStockMapper;

    private final WarehouseStorageLocationMapper warehouseStorageLocationMapper;

    private final WarehouseMapper warehouseMapper;

    /**
     * 获取出库明细分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<OutboundOrderDetailVO>} 出库明细分页列表
     */
    @Override
    public IPage<OutboundOrderDetailVO> getOutboundOrderDetailPage(OutboundOrderDetailQuery queryParams) {
        Page<OutboundOrderDetailVO> pageVO = this.baseMapper.getOutboundOrderDetailPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }

    /**
     * 获取出库明细表单数据
     *
     * @param id 出库明细ID
     * @return 出库明细表单数据
     */
    @Override
    public OutboundOrderDetailForm getOutboundOrderDetailFormData(Long id) {
        OutboundOrderDetail entity = this.getById(id);
        return outboundOrderDetailConverter.toForm(entity);
    }


    /**
     * 新增出库明细
     *
     * @param formData 出库明细表单对象
     * @param ipAddr
     * @return 是否新增成功
     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public Result saveOutboundOrderDetail(OutboundOrderDetailForm formData, String ipAddr) {
//        Integer quantity = formData.getQuantity();
//
//        ProductBatch productBatch = productBatchMapper.selectById(formData.getBatchId());
//        if (productBatch == null) {
//            return Result.failed("没有对应的库存");
//        }
//        List<WarehouseBatchStock> warehouseBatchStocks = warehouseBatchStockMapper.selectList(new LambdaQueryWrapper<WarehouseBatchStock>().eq(WarehouseBatchStock::getBatchId, formData.getBatchId()));
//        if (warehouseBatchStocks == null || warehouseBatchStocks.size() == 0) {
//            return Result.failed("没有对应的仓库批次库存");
//        }
//        Warehouse warehouse = warehouseMapper.selectById(warehouseBatchStocks.get(0).getWarehouseId());
//        WarehouseStorageLocation warehouseStorageLocation = warehouseStorageLocationMapper.selectById(warehouseBatchStocks.get(0).getStorageLocationId());
//        if (productBatch.getExpiryDate().isBefore(LocalDate.now())) {
//            return Result.failed("所选批次过了有效期");
//        }
//        if (quantity > productBatch.getQuantityProduced()) {
//            return Result.failed("超过库存数");
//        }
//        OutboundOrder outboundOrder = outboundOrderMapper.selectById(formData.getOutboundOrderId());
//        if (outboundOrder == null) {
//            return Result.failed("没有对应的出库单");
//        }
//        Order order = orderMapper.selectById(formData.getOrderId());
//        if (order == null) {
//            return Result.failed("订单不存在");
//        }
//        if (order.getStatus().intValue() == OrderStatusEnum.Status2.getValue()) {
//            if (outboundOrder.getStatus().equals("已审核") || outboundOrder.getStatus().equals("发货中")) {
//                OrderItem orderItem = orderItemMapper.selectById(formData.getOrderItemId());
//                if (orderItem == null) {
//                    return Result.failed("找不到对应的商品订单");
//                }
//                if (orderItem.getQuantity() - orderItem.getCompletedQuantity() < formData.getQuantity()) {
//                    return Result.failed("货品超发");
//                }
//                orderItem.setCompletedQuantity(orderItem.getCompletedQuantity() + formData.getQuantity());
//                orderItemMapper.updateById(orderItem);
//                OutboundOrderDetail entity = new OutboundOrderDetail();
//                entity.setOutboundOrderId(formData.getOutboundOrderId());
//                entity.setBatchId(formData.getBatchId());
//                entity.setQuantity(formData.getQuantity());
//                entity.setStorageLocation("仓库：" + warehouse.getWarehoustName() + "-库位：" + warehouseStorageLocation.getStorageLocation());
//                entity.setCreateBy(SecurityUtils.getUserStrId());
//                entity.setCreateIp(ipAddr);
//                entity.setCreateTime(LocalDateTime.now());
//                entity.setEms(formData.getEms());
//                entity.setEmsnumber(formData.getEmsnumber());
//                entity.setOrderItemId(formData.getOrderItemId());
//                entity.setStatus("已发货");
//                int insert = this.baseMapper.insert(entity);
//                if (insert != 1) {
//                    return Result.failed("新增失败");
//                }
//                return Result.success("新增成功");
//            } else {
//                return Result.failed("出库单状态不能发货");
//            }
//        }
//        return Result.failed("订单状态不能发货");
//
//    }

    /**
     * 更新出库明细
     *
     * @param id       出库明细ID
     * @param formData 出库明细表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateOutboundOrderDetail(Long id, OutboundOrderDetailForm formData) {
        OutboundOrderDetail entity = outboundOrderDetailConverter.toEntity(formData);
        return this.updateById(entity);
    }

    /**
     * 删除出库明细
     *
     * @param ids 出库明细ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteOutboundOrderDetails(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的出库明细数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

}
